#!/usr/bin/env python3
"""
管理员账户初始化脚本
"""

import os
import sys

def init_admin():
    """初始化管理员账户"""
    print("管理员账户初始化")
    print("=" * 30)
    
    try:
        # 导入必要的模块
        from flask import Flask
        from flask_sqlalchemy import SQLAlchemy
        from werkzeug.security import generate_password_hash
        
        # 创建临时应用
        app = Flask(__name__)
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///ai_ssq.db'
        app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
        
        # 初始化数据库
        db = SQLAlchemy()
        db.init_app(app)
        
        # 定义用户模型
        class User(db.Model):
            __tablename__ = 'users'
            id = db.Column(db.Integer, primary_key=True)
            username = db.Column(db.String(80), unique=True, nullable=False)
            password_hash = db.Column(db.String(120), nullable=False)
            created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
            updated_at = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp())
            
            def set_password(self, password):
                self.password_hash = generate_password_hash(password)
            
            def check_password(self, password):
                from werkzeug.security import check_password_hash
                return check_password_hash(self.password_hash, password)
        
        with app.app_context():
            # 创建表
            db.create_all()
            print("✓ 数据库表创建成功")
            
            # 检查是否已存在管理员账户
            admin = User.query.filter_by(username='admin').first()
            if admin:
                print("✓ 管理员账户已存在")
                print(f"  用户名: {admin.username}")
                print(f"  创建时间: {admin.created_at}")
            else:
                # 创建管理员账户
                admin = User(username='admin')
                admin.set_password('admin123')
                db.session.add(admin)
                db.session.commit()
                print("✓ 管理员账户创建成功")
                print("  用户名: admin")
                print("  密码: admin123")
            
            # 显示所有用户
            users = User.query.all()
            print(f"\n当前用户数量: {len(users)}")
            for user in users:
                print(f"  - {user.username} (ID: {user.id})")
                
    except Exception as e:
        print(f"✗ 初始化失败: {e}")
        return False
    
    return True

if __name__ == '__main__':
    success = init_admin()
    if success:
        print("\n✓ 管理员账户初始化完成")
    else:
        print("\n✗ 管理员账户初始化失败")
    
    input("\n按回车键退出...") 